package main

import (
	"fmt"
	"net"
	"net/http"
	"os"
	"strings"
)

func main() {
	http.HandleFunc("/healthz", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Println("healthz")
		writer.WriteHeader(http.StatusOK)
	})

	http.HandleFunc("/demo/header", func(writer http.ResponseWriter, request *http.Request) {
		//请求头
		headers := request.Header
		for key, values := range headers {
			if len(values) > 0 {
				writer.Header().Add(key, values[0])
			}
		}
		//VERSION
		ver := os.Getenv("VERSION")
		writer.Header().Add("VERSION", ver)

		resp, err := http.Get("https://www.baidu.com")
		if err != nil {
			fmt.Println(err)
			writer.WriteHeader(http.StatusInternalServerError)
			return
		}

		clientIp := clientIP(request)
		fmt.Printf("==== %s %d\n", clientIp, resp.StatusCode)
		writer.Write([]byte("success"))
	})

	http.ListenAndServe(":18081", nil)
}

func clientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}

	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}

	return ""
}
